const Koa = require('koa')
const app = new Koa()
const mongoose = require('mongoose')
const bcrypt = require('bcrypt') // 加密
const Router = require('koa-router') // 路由
const bodyParser = require('koa-bodyparser') // 接收前端数据
const cors = require('koa2-cors')
const {
  connect,
  initSchemas
} = require('./database/init')

let user = require('./api/user')
let router = new Router()
router.use('/user',user.routes())

app.use(router.routes())
  .use(router.allowedMethods())
  .use(bodyParser())
  .use(cors())

// 立即执行
;(async () => {
  await connect()
  initSchemas()
  const User = mongoose.model('User')

  bcrypt.hash('123456',10,(err,hash)=>{
    bcrypt.compare('1234567', hash).then((res) => {
    })
  })
  // let oneUser = new User({userName:'嘿嘿man',password:'12345678'})
    
  // oneUser.save().then(()=>{
  //   console.log('插入成功');
  // })
  // 读取数据
  // let users = await User.findOne({}).exec()
  // console.log(users);
})()

app.use(async (ctx) => {
  ctx.body = '<h1>hello Koa2</h1>'
})

app.listen(3000, () => {
  console.log('服务已启动');
})